<?php


namespace App\Exceptions;


use App\Enum\APIEnum;

class APIHttpException extends \Exception
{
    private static $_msg = '';
    private static $_code = 0;
    private static $_obj = [];
    private static $_trace = [];
    /*定义需要需绑定的Code状态码跟Http状态码关系*/
    private static $_httpCode = [
        /*code=>httpStatus*/
        APIEnum::LOGIN_VOID['code'] => 'HTTP/1.1 401 Unauthorized',
    ];

    /**
     * APIHttpException constructor.
     * * @param string $msg
     *
     * @param int   $code
     * @param array $obj
     * @param array $trace
     */
    public function __construct(string $msg = '', int $code = 403, array $obj = [], array $trace = [], bool $handler = false)
    {
        if ($handler === false) {
            self::$_msg = $msg;
            self::$_code = $code;
            self::$_obj = $obj;
        }
        self::$_trace = $trace;
        /*如果是Handler调用,则直接返回*/
        if ($handler === true) {
            $this->handleError();
        }
        parent::__construct(self::$_msg, self::$_code);
    }


    /**
     * handleError
     */
    public function handleError()
    {
        header('Content-Type:application/json;charset=utf-8');
        $code = self::$_code === 0 ? APIEnum::ERR['code'] : self::$_code;
        if (isset(self::$_httpCode[$code])) {
            @header(self::$_httpCode[$code]);
        }
        /*输出异常,并退出当前脚本*/
        exit(json_encode(array_merge([
            'code' => $code,
            'msg'  => empty(self::$_msg) ? APIEnum::ERR['msg'] : self::$_msg,
            'obj'  => (object) self::$_obj,
        ], self::$_trace), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    }


    /**
     * API正常响应:必须在Controllers层调用
     *
     * @param array  $obj  要返回的数据
     * @param array  $enum use App\Enum 定义好的APIEnum,默认使用 SUCCESS
     * @param string $msg  接口msg描述
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function success(array $obj = [], array $enum = APIEnum::SUCCESS, string $msg = '')
    {
        return response()
            ->json([
                'code' => $enum['code'],
                'msg'  => empty($msg) ? $enum['msg'] : $msg,
                'obj'  => (object) $obj
            ], 200)
            ->header('Content-Type', 'application/json;charset=utf-8')
            ->setEncodingOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //JSON_FORCE_OBJECT
    }


}





/**
 * APIHttpException.php
 *
 * 说明:
 *
 * 修改历史
 * ----------------------------------------
 * 2021/3/8 15:00:00   操作:创建
 **/
